import React from 'react';
import {Link} from 'dva/router';
import {defaultImg} from '../../config/config';
import {Table, Badge, Divider, Popconfirm, Button, Modal, Avatar, Tooltip, Icon, Menu, Dropdown} from 'antd';
import StatusDescModal from './StatusDescModal';

import styles from './ProjectTable.less';

export default class ProjectTable extends React.PureComponent {

  constructor(props) {
    super(props);

    this.state = {
      id: 0,
      level: 0,
      status: 0,
    };
  }

  cleanSelectedKeys = () => {
    this.props.dispatch({
      type: 'project/cleanSelectedKeys',
    });
  };

  showBatchDeleteConfirm = () => {
    const {dispatch, selectedRowKeys} = this.props;

    Modal.confirm({
      title: `确定删除已选中 ${selectedRowKeys.length} 项?`,
      content: 'Some descriptions',
      okText: 'Yes',
      okType: 'danger',
      cancelText: 'No',
      onOk() {
        dispatch({
          type: 'project/removeByIds',
        });
      },
      onCancel() {
        console.log('Cancel');
      },
    });
  };

  remove = (id) => {
    this.props.dispatch({
      type: 'project/remove',
      payload: id,
    });
  };

  toggleRecom = (id, is_recom) => {
    this.props.dispatch({
      type: 'project/setRecom',
      payload: {
        id,
        is_recom: is_recom ? 1 : 0,
      },
    });
  };

  handleLevelMenuClick = (id, key) => {
    const level = Number(key);
    this.props.dispatch({
      type: 'project/saveLevel',
      payload: {
        id,
        level,
      },
    });
  };

  handleStatusMenuClick = (id, key) => {
    const status = Number(key);
    if (status === 2) {
      this.setState({
        id,
        status,
      });
      this.props.dispatch({
        type: 'project/showStatusDescModal',
      });
    } else {
      this.props.dispatch({
        type: 'project/saveStatus',
        payload: {
          id,
          status,
          status_desc: '',
        },
      });
    }
  };

  render() {
    const {dispatch, loading, list, pagination, selectedRowKeys, query, onTableChange} = this.props;
    const {id, level, status} = this.state;

    const levelList = ['无', '白银', '黄金', '铂金', '钻石'];
    const levelColors = ['gray', 'green', 'orange', 'magenta', 'purple'];
    const levelMenuItems = levelList.map((item, index) => <Menu.Item key={index}>{item}</Menu.Item>);
    const statusList = ['未审核', '通过', '未通过', '审核中'];
    const statusMap = ['default', 'success', 'error', 'processing'];
    const statusMenuItems = statusList.map((item, index) => <Menu.Item key={index}>{item}</Menu.Item>);

    const columns = [{
        title: '图片',
        dataIndex: 'img',
        render: text => <Avatar shape="square" size="large" src={text || defaultImg}/>,
      width: 50,
    }, {
      title: '名称/区域',
      render: record => (
        <div>
          <Tooltip placement="topLeft" title={record.name}>
            <Link className={styles.name} to={`project/${record.id}/edit`}>{record.name}</Link>
          </Tooltip>
          <span className={styles.subname}>{record.no} {record.province}</span>
        </div>
      ),
      width: 250,
    }, {
      title: '发布人',
      dataIndex: 'customer_name',
    }, {
      title: '分类',
      render: record => record.cname2 ? <span>{record.cname1} / {record.cname2}</span> : <span>{record.cname1}</span>,
    }, {
      title: '价格',
      dataIndex: 'price',
      render: text => <span className={styles.price}>￥{text}</span>,
      sorter: true,
      sortOrder: query.sort === 'price' && query.order,
    }, {
      title: '面议',
      dataIndex: 'negotiable',
      render: val => val ? <Icon type="check-circle" theme="filled" className={styles.lightgreen} /> : <Icon type="minus-circle" theme="filled" className={styles.lightgray} />,
    }, {
      title: '推荐',
      render: record => (
        <a onClick={() => this.toggleRecom(record.id, !record.is_recom)}>
          {
            record.is_recom
              ? <Icon type="check-circle" theme="filled" className={styles.lightgreen} />
              : <Icon type="minus-circle" theme="filled" className={styles.lightgray} />
          }
        </a>
      ),
    }, {
      title: '等级',
      dataIndex: 'level',
      filters: [{
        text: level[0],
        value: 0,
      }, {
        text: level[1],
        value: 1,
      }, {
        text: level[2],
        value: 2,
      }, {
        text: level[3],
        value: 3,
      }],
      filterMultiple: false,
      filteredValue: new Array(query.status || '') || null,
      render: (val, record) => <div>
        <Dropdown overlay={<Menu onClick={({key}) => this.handleLevelMenuClick(record.id, key)}>{levelMenuItems}</Menu>} trigger={['click']}>
          <a className="ant-dropdown-link" href="#">
            <span style={{color: levelColors[val]}}>{levelList[val]}</span> <Icon type="down"/>
          </a>
        </Dropdown>
      </div>,
    }, {
      title: '状态',
      dataIndex: 'status',
      filters: [{
        text: status[0],
        value: 0,
      }, {
        text: status[1],
        value: 1,
      }, {
        text: status[2],
        value: 2,
      }, {
        text: status[3],
        value: 3,
      }],
      filterMultiple: false,
      filteredValue: new Array(query.status || '') || null,
      render: (val, record) => <div>
        <Dropdown overlay={<Menu onClick={({key}) => this.handleStatusMenuClick(record.id, key)}>{statusMenuItems}</Menu>} trigger={['click']}>
          <a className="ant-dropdown-link" href="#">
            <Badge status={statusMap[val]} text={statusList[val]}/> <Icon type="down"/>
          </a>
        </Dropdown>
        {(val === 2) && <Tooltip title={record.status_desc}>
          <Icon type="question-circle-o"/>
        </Tooltip>}
      </div>,
    }, {
      title: '更新时间',
      dataIndex: 'updated_at',
      sorter: true,
      sortOrder: query.sort === 'updated_at' && query.order,
    }, {
      title: '操作',
      render: record => (
        <div>
          <Link to={`project/${record.id}/edit`}>编辑</Link>
          <Divider type="vertical"/>
          <Popconfirm title="是否要删除此项？" onConfirm={() => this.remove(record.id)}>
            <a>删除</a>
          </Popconfirm>
        </div>
      ),
    }];

    const tableProps = {
      loading: loading.effects['project/bGetPage'],
      columns,
      dataSource: list,
      rowKey: record => record.id,
      rowSelection: {
        selectedRowKeys,
        onChange: keys => {
          dispatch({
            type: 'project/bUpdateState',
            payload: {
              selectedRowKeys: keys,
            },
          });
        },
        getCheckboxProps: record => ({
          disabled: record.disabled,
        }),
      },
      pagination,
      onChange: onTableChange,
    };

    const statusProps = {
      dispatch,
      id,
      status,
    };

    return (
      <div className={styles.projectTable}>
        <div className={styles.toolBar}>
          <Link to={`project/new`}><Button type="primary" icon="plus" className={styles.MR8}>新建</Button></Link>
          {selectedRowKeys.length > 0 &&
          <span className={styles.pullRight}>
							<span className={styles.MR8}>{`已选 ${selectedRowKeys.length} 项 `}</span>
							<Button type="danger" className={styles.MR8} onClick={this.showBatchDeleteConfirm}>批量删除</Button>
							<Button onClick={this.cleanSelectedKeys}>取消选择</Button>
						</span>
          }
        </div>
        <Table {...tableProps} />
        <StatusDescModal {...statusProps} />
      </div>
    );
  }
}
